package com.woorigil.social;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class StreamUtils {
	public static String toString(InputStream is, String encoding) throws Exception {
		BufferedReader br = null;
		StringBuffer buffer = new StringBuffer();
		boolean isSubstring = false;

		try {
			br = new BufferedReader(new InputStreamReader(is, encoding));
			String line; 
			while ((line = br.readLine()) != null) {
				buffer.append(line).append("\n");
				isSubstring = true;
			}
		} finally {
			if (is != null) {
				is.close();
			}
			if (br != null) {
				br.close();
			}
		}
		return (isSubstring) ? buffer.substring(0, buffer.length() - 1) : buffer.toString();
	}
	
	public static InputStream toInputStream(String str, String encoding) throws UnsupportedEncodingException {
		byte[] bytes = str.getBytes(encoding);
		return new ByteArrayInputStream(bytes);
	}
}
